# -*- coding: utf-8 -*-
from . import BaseController
from backend.libs import myjson as json
from backend.models import Role, Resource, RoleResource


class RoleListController(BaseController):

    def get(self):
        r = Role.objects
        role_name = self.get_argument('roleName', '')
        if role_name:
            r = r.filter(name__contains=role_name)

        disabled = self.int_argument('disabled', 0)
        r = r.filter(disabled=disabled).order_by('show_order')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(r.all(), number_per_page=number_per_page, m2m_fields=['resources'])

        return self.render_json(data=paginator)


class RoleOperatorsController(BaseController):

    def get(self):
        role_id = self.int_argument('id', 0)
        r = Role.objects.filter(id=role_id).first()
        if not r:
            return self.render_json(data={'operators': []})
        
        return self.render_json(data={'operators': [o.to_option_dict() for o in r.operators.all()]})


class RoleListAllController(BaseController):

    def get(self):
        roles = Role.objects.order_by('show_order').all()
        data = {'roles': [ r.to_dict() for r in roles ]}
        return self.render_json(data=data)


class RoleResourcesController(BaseController):

    def get(self):
        id = self.int_argument('id', 0)
        if id <= 0:
            return self.render_json(code=1003, msg='角色ID错误')
        r = Role.objects.filter(id=id).first()
        data = []
        if r:
            data = [f.to_dict() for f in r.resources.filter(disabled=0).all()] if r else []

        return self.render_json(data={'resources':data})


class CreateRoleController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        if not data['name']:
            return self.render_json(code=1001, msg='角色名称不能为空')
        role_id = data['id']

        role = Role() if int(role_id) <= 0 else Role.objects.filter(id=role_id).first()
        role.name = data['name']
        role.description = data['description']
        role.disabled = data['disabled']
        role.show_order = data['show_order']
        role.save()
        return self.render_json(data=role.to_dict())


class CreateRoleResourceRelController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        if not data['resourceIds']:
            return self.render_json(code=1001, msg='至少选择一个资源')
        role_id = data['roleId']
        if int(role_id) <= 0:
            return self.render_json(code=1001, msg='角色ID错误')

        role = Role.objects.filter(id=role_id).first()
        if not role:
            return self.render_json(code=1001, msg='没有找到指定ID的角色数据')

        # 删除所有原来的权限
        RoleResource.objects.filter(role_id=role_id).all().delete()
        print('** ' * 50)
        print(data['resourceIds'])
        resource_list = Resource.objects.filter(id__in=data['resourceIds']).all()
        for r in resource_list:
            role_resource = RoleResource()
            role_resource.role = role
            role_resource.resource = r
            role_resource.save()
        return self.render_json()


class DeleteRoleController(BaseController):

    def post(self, role_id):
        role_id = int(role_id)
        if role_id > 0:
            role = Role.objects.filter(id=role_id).first()
            if role:
                role.delete()

        return self.render_json()
